package cn.market.service.privilege.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import javax.persistence.Query;

import org.springframework.stereotype.Service;

import cn.market.bean.QueryResult;
import cn.market.bean.privilege.Department;
import cn.market.bean.privilege.Employee;
import cn.market.bean.user.Market;
import cn.market.service.base.DaoSupport;
import cn.market.service.privilege.DepartmentService;

@Service
public class DepartmentServiceBean extends DaoSupport<Department> implements DepartmentService {

	@Override
	public void delete(Serializable... entityids) {
		for(Serializable id : entityids){
			Department department = this.find(id);
			for(Employee employee : department.getEmployees()){
				employee.setDepartment(null);
			}
			em.remove(department);
		}
	}

	@Override
	public void save(Department entity) {
		entity.setDepartmentid(UUID.randomUUID().toString());
		super.save(entity);
	}

	@Override
	public List<Department> getAllDepartment(Integer marketid) {
		List<Department> departments = new ArrayList<Department>();
		 String sql = "select d.departmentid,d.name,m.name,m.address from Department d,Market m where d.belongToMarket.id = m.id and d.belongToMarket.id=?1";
		 Query query = em.createQuery(sql);
		 query.setParameter(1, marketid);
		 List list = query.getResultList();
		 if(list != null && list.size()>0){
			 for(int i = 0;i<list.size();i++){
				 Object [] obj = (Object [])list.get(i);
				 Department department = new Department();
				 department.setDepartmentid(String.valueOf(obj[0]));
				 department.setName(String.valueOf(obj[1]));
				 Market market = new Market();
				 market.setName(String.valueOf(obj[2]));
				 market.setAddress(String.valueOf(obj[3]));
				 market.setId(marketid);
				 department.setBelongToMarket(market);
				 departments.add(department);
			 }
		 }
		return departments;
	}

	@Override
	public QueryResult<Department> getAllDepartment(String sql, String where,
			int first, int max, Object[] params,
			LinkedHashMap<String, String> orderby) {
		 QueryResult<Department>  qr = new  QueryResult<Department> ();
		 List<Department> departments = new ArrayList<Department>();
		List list = getScrollData(sql, where, first, max, params, orderby);
		if(list != null && list.size()>0){
			for(int i=0;i<list.size();i++){
				Object [] obj = (Object [])list.get(i);
				Department department = new Department();
				department.setDepartmentid(String.valueOf(obj[0]));
				department.setName(String.valueOf(obj[1]));
				departments.add(department);
			}
			qr.setResultlist(departments);
		}
		return qr;
	}

}
